package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.extension.conditions.update.UpdateChainWrapper;
import com.hmdp.dto.Result;
import com.hmdp.entity.SeckillVoucher;
import com.hmdp.entity.VoucherOrder;
import com.hmdp.mapper.VoucherOrderMapper;
import com.hmdp.service.ISeckillVoucherService;
import com.hmdp.service.IVoucherOrderService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.RedisIdWorker;
import com.hmdp.utils.SimpleRedisLock;
import com.hmdp.utils.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.aop.framework.AopContext;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.connection.stream.*;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.time.Duration;
import java.time.LocalDateTime;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.*;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
@Slf4j
public class VoucherOrderServiceImpl extends ServiceImpl<VoucherOrderMapper, VoucherOrder> implements IVoucherOrderService {

    @Resource
    private ISeckillVoucherService seckillVoucherService;
    @Resource
    private RedisIdWorker redisIdWorker;
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    private RedissonClient redissonClient;

    private String queueName = "stream.orders";
    IVoucherOrderService proxy;
    //注入 lua 脚本
    private static final DefaultRedisScript<Long> SECKILL_SCRIPT;
    static {
        SECKILL_SCRIPT = new DefaultRedisScript<>();
        SECKILL_SCRIPT.setLocation(new ClassPathResource("seckill.lua"));
        SECKILL_SCRIPT.setResultType(Long.class);
    }
    //阻塞队列
    //private BlockingQueue<VoucherOrder> orderTask = new ArrayBlockingQueue<>(1024 * 1024);
    //线程池
    private static final ExecutorService SECKILL_ORDER_EXECTUOR = Executors.newSingleThreadExecutor();

    @PostConstruct
    private void init() {
        //在这个类初始化完毕后,立即执行任务
        //这个线程池是单个的独立线程
        SECKILL_ORDER_EXECTUOR.submit(new VoucherOrderHandler());
    }

    /**
     * 异步  的Stream从消息队列中获取数据
     */

    private  class VoucherOrderHandler implements Runnable{
        @Override
        public void run() {
            while (true) {
                try {
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                try {
                    //1.获取消息队列中的信息 XREADGROUP GRPUP g1 c1 COUNT 1 BLOCK 2000 STREAMS.ORDER > (最近一条未消费的消息)
                    List<MapRecord<String, Object, Object>> list = stringRedisTemplate.opsForStream().read(
                            Consumer.from("G1", "C1"),
                            StreamReadOptions.empty().count(1).block(Duration.ofSeconds(2)),
                            StreamOffset.create(queueName, ReadOffset.lastConsumed())

                    );
                    //2.判断消息是否获取成功
                    if(list == null || list.isEmpty()) {
                        //2.1.如果获取失败,说明当前队列中没有消息,直接继续下次循环
                        continue;
                    }
                    //3.解析消息中的订单 id
                    MapRecord<String, Object, Object> record = list.get(0);
                    Map<Object, Object> value = record.getValue();
                    VoucherOrder voucherOrder = BeanUtil.fillBeanWithMap(value, new VoucherOrder(), true);
                    //4.如果获取成功,直接下单
                    handleVoucherOrder(voucherOrder);
                    //5.ACK确认
                    stringRedisTemplate.opsForStream().acknowledge(queueName,"G1",record.getId());
                } catch (Exception e) {
                    log.error("处理订单异常:",e);
                    handlePendingList();
                }

            }
        }
    }

    private void handlePendingList()  {
        while (true) {
            try {
                //1.获取pending - list 中的信息 XREADGROUP GRPUP g1 c1 COUNT 1 STREAMS.ORDER 0(读取pending-list中未消费的消息)
                List<MapRecord<String, Object, Object>> list = stringRedisTemplate.opsForStream().read(
                        Consumer.from("G1", "C1"),
                        StreamReadOptions.empty().count(1),
                        StreamOffset.create(queueName, ReadOffset.from("0"))

                );
                //2.判断消息是否获取成功
                if(list == null || list.isEmpty()) {
                    //2.1.如果获取失败,说明pending - list中没有消息,直接继续下次循环
                    break;
                }
                //3.解析消息中的订单 id
                MapRecord<String, Object, Object> record = list.get(0);
                Map<Object, Object> value = record.getValue();
                VoucherOrder voucherOrder = BeanUtil.fillBeanWithMap(value, new VoucherOrder(), true);
                //4.如果获取成功,直接下单
                handleVoucherOrder(voucherOrder);
                //5.ACK确认
                stringRedisTemplate.opsForStream().acknowledge(queueName,"G1",record.getId());
            } catch (Exception e) {

                log.error("处理订单异常:",e);
            }

        }
    }

    /*
    //任务  在这个类初始化完毕后,任务应该立即执行
    private  class VoucherOrderHandler implements Runnable{
        @Override
        public void run() {
            while (true) {
                try {
                    //1.获取队列中的订单信息
                    VoucherOrder voucherOrder = orderTask.take();
                    //2.创建订单
                    handleVoucherOrder(voucherOrder);
                } catch (Exception e) {
                    log.error("处理订单异常:",e);
                }

            }
        }
    }

     */
    private void handleVoucherOrder(VoucherOrder voucherOrder) throws InterruptedException {
        //异步的执行消息队列中的操作,写入MySQL数据库

        //1.获取用户id
        Long userId = voucherOrder.getUserId();
        //2.创建锁对象  针对不同用户进行分别存储
        //SimpleRedisLock lock = new SimpleRedisLock("order:" + userId,stringRedisTemplate);
        RLock lock = redissonClient.getLock("lock:order::" + userId);
        //3.判断是否获取锁成功
        boolean isLock = lock.tryLock(1L, TimeUnit.SECONDS);
        if (!isLock) {
            log.error("不可以重复下单");
        }
        try {
            //获取和事务有关的代理对象
             proxy.createVoucherOrder(voucherOrder);
        } finally {
            lock.unlock();
        }
    }


    @Override
    //设计两张表的操作 加上事务.,方便回滚
    public Result seckillVoucher(Long voucherId) throws InterruptedException {
        //获取当前用户
        Long userId = UserHolder.getUser().getId();
        long orderId = redisIdWorker.nextId("order");

        //1.执行 lua 脚本  此处判断完如果有下单资格,就会向Redis中的stream.orders这个队列中添加信息
        Long result = stringRedisTemplate.execute(
                SECKILL_SCRIPT,
                Collections.emptyList(),
                voucherId.toString(), userId.toString(),String.valueOf(orderId)
        );
        //2.判断结果是不是0    0成功   1库存不足  2用户已经购买过了
        int r = result.intValue();
        if(r != 0) {
            //2.1.不是 0,代表没有购买资格
            return Result.fail(r == 1 ? "库存不足" : "不能重复下单(＾Ｕ＾)~ＹＯ");
        }
        //往数据库中的操作,放到了线程池中了

        //3.获取代理对象
        proxy = (IVoucherOrderService) AopContext.currentProxy();

        //4.返回订单id
        return Result.ok(orderId);
    }

    /*
    @Override
    //设计两张表的操作 加上事务.,方便回滚
    public Result seckillVoucher(Long voucherId) throws InterruptedException {
        //1.查询秒杀券
        SeckillVoucher voucher = seckillVoucherService.getById(voucherId);
        //2.判断秒杀是否开始
        if (voucher.getBeginTime().isAfter(LocalDateTime.now())) {
            //如果秒杀的开始时间在当前时间之后,说明秒杀没有开始
             return Result.fail("秒杀尚未开始..");
        }
        //3.判断秒杀是否已经结束
        if (voucher.getEndTime().isBefore(LocalDateTime.now())) {
            //如果秒杀结束时间在当前时间之前,说明秒杀结束了
            return Result.fail("秒杀已结束...");
        }
        //4.判断库存是否充足
        if (voucher.getStock() < 1) {
            return Result.fail("库存不足..");
        }
        Long userId = UserHolder.getUser().getId();

        //创建锁对象  针对不同用户进行分别存储
        //SimpleRedisLock lock = new SimpleRedisLock("order:" + userId,stringRedisTemplate);
        RLock lock = redissonClient.getLock("order:" + userId);
        boolean isLock = lock.tryLock(1L, TimeUnit.SECONDS);
        if (!isLock) {
            return Result.fail("不允许重复下单");
        }
        try {
            //获取和事务有关的代理对象
            IVoucherOrderService proxy = (IVoucherOrderService) AopContext.currentProxy();
            return proxy.createVoucherOrder(voucherId);
        } finally {
            lock.unlock();
        }

    }

     */


    @Transactional
    public void createVoucherOrder(VoucherOrder voucherOrder) {
        //5.实现一人一单功能
        Long voucherId = voucherOrder.getVoucherId();
        //注意:当前创建订单信息是在线程池中,也就是子线程.那么是拿不到 ThreadLocal 中的user的.
        //     所以从 voucherOrder 中获取
        Long userId = voucherOrder.getUserId();
            //5.1查询订单是否存在
            int count = Math.toIntExact(query().eq("user_id", userId).eq("voucher_id", voucherId).count());
            if (count > 0) {
                //用户已经购买过了
                log.error("用户已经购买过了!");
            }
            //5.2扣减库存
            boolean success = seckillVoucherService.update()
                    .setSql("stock = stock - 1")  // set stock = stock - 1 where voucher_id = ? and stock > 0

                    .eq("voucher_id", voucherId).gt("stock", 0)
                    .update();

            if (!success) {
                //扣减失败
                log.error("库存不足!");
            }
            save(voucherOrder);

        }

}
